/**
 * cn.ucox.web.modules.api.controller.OnlinePay
 *
 * @author chenw
 * @create 16/3/8.08:58
 * @email javacspring@hotmail.com
 */

package com.oceansoft.mobile.econsole.modules.pay;

import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

/**
 * 在线支付
 *
 * @author chenw
 * @create 16/3/8 08:58
 * @email javacspring@gmail.com
 */
@Controller
@RequestMapping("api/v1/pay")
public class ApiOnlinePay {

    private final Pattern bizNo = Pattern.compile("\\w{22}");
    private final Pattern amount = Pattern.compile("(\\d\\.)?\\d{1,}");
    private final Pattern time = Pattern.compile("\\d{14}");

    @RequestMapping(value = "online", method = GET)
    public String gotoPayIndex() {
        return "pay/index";
    }

    @RequestMapping(value = "wap", method = GET)
    public String gotoPayIndex(@RequestParam("slh") String slh,//受理编号
                               @RequestParam("sxmc") String sxmc,//事项名称
                               @RequestParam("zfje") String zfje,//支付金额
                               @RequestParam(value = "sljgdm", required = false) String sljgdm,//受理机构代码
                               @RequestParam("sljgmc") String sljgmc,//受理机构名称
                               @RequestParam(value = "slsj") String slsj,//受理时间
                               @RequestParam("yxsj") int yxsj,//有效时间
                               @RequestParam(value = "lxdh", required = false) String lxdh,//联系电话
                               Model model) {
        Map<String, Object> params = new HashMap();
        //参数校验
        if (null == slh || !bizNo.matcher(slh).matches()) {
            model.addAttribute("error", "受理编号错误!");
            return "pay/pay-index";
        }
        if (null == zfje || !amount.matcher(zfje).matches()) {
            model.addAttribute("error", "支付金额有误!");
            return "pay/pay-index";
        }
        if (null == slsj || !time.matcher(slsj).matches()) {
            model.addAttribute("error", "受理时间有误!");
            return "pay/pay-index";
        }

        try {
            SimpleDateFormat formatter = new SimpleDateFormat("YYYYMMddHHmmss");
            Date expire = formatter.parse(slsj);
            if (expire.getTime() + yxsj * 60000 > new Date().getTime()) {
                params.put("error", "已过支付有效期!");
                return "pay/pay-index";
            }
            model.addAttribute("expire", new SimpleDateFormat("YYYY-mm-dd HH:mm:ss").format(expire));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        model.addAttribute("mobile", lxdh);
        model.addAttribute("unitName", sljgmc);

        String secretKey = "A20160204";

        params.put("bizNo", slh);
        params.put("amt", zfje);

        params.put("version", "1.0.0");
        params.put("charset", "UTF-8");
        params.put("transType", "S1");
        params.put("catCode", "0106001");

        try {
            params.put("settleDesc", new String(sxmc.getBytes("UTF-8")));
            params.put("catName", new String("户政缴费".getBytes("UTF-8")));
            params.put("appName", new String("公安厅缴费平台".getBytes("UTF-8")));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        params.put("appNo", "fb781175b38b4778baa6e8429a73bd15");
        params.put("frontUrl", "http://www.qq.com/");
        params.put("backEndUrl", "http://218.27.41.243:81/AutoResiveMessage.aspx");
        params.put("bizDate", new SimpleDateFormat("YYYYMMddHHmmss").format(new Date()));
        params.put("bankNo", "906");
        params.put("ccy", "001");
        params.put("payType", "MW");

        StringBuilder sb = new StringBuilder();
        params.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByKey(Comparator.naturalOrder()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (key, val) -> key, LinkedHashMap::new))
                .forEach((key, val) -> {
                    try {
                        sb.append(String.format("&%s=%s", key, new String(val.toString().getBytes("UTF-8"))));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                });

        System.out.println("URL参数:" + sb.toString().replaceFirst("&", ""));
        System.out.println(" SK签名:" + StringUtil.md5Hex(secretKey));
        System.out.println("签名参数:" + String.format("%s&%s", sb.toString().replaceFirst("&", ""), StringUtil.md5Hex(secretKey)));
        //计算签名
        String signature = StringUtil.md5Hex(String.format("%s&%s", sb.toString().replaceFirst("&", ""), StringUtil.md5Hex(secretKey)));
        System.out.println("签名结果:" + signature);
        params.put("signMethod", "MD5");
        params.put("signature", signature);

        System.out.println("表单参数:" + JSON.toJSONString(params));

        model.addAllAttributes(params);
        params.clear();
        return "pay/pay-index";
    }

}
